#!/bin/bash
#================================================================
#  Author: Liu Hanxu
#  Date: 2025-05-01
#  Description: send & run send.sh on each remote server
#================================================================

SEND_SCRIPT=$(realpath send.sh)
SERVER_LIST=$(realpath ip_list.txt)
REMOTE_PATH=${3:-/tmp}

# 检查依赖命令
command -v sshpass >/dev/null 2>&1 || { 
    echo "请先安装sshpass：sudo yum install sshpass -y 或 sudo apt-get install sshpass"
    exit 1
}

# 读取服务器列表
readarray -t servers < "$SERVER_LIST"
declare -p servers

# 分发脚本到所有服务器
for server in "${servers[@]}"; do
    echo -e "\033[33m正在分发到 $server ...\033[0m"
    sshpass -p 'l' scp -o StrictHostKeyChecking=no \
        "$SEND_SCRIPT" lhx@"$server":"$REMOTE_PATH/" && {
        echo -e "\033[32m成功分发到 $server\033[0m"
    } || {
	echo -e "\033[31m分发到 $server 失败\033[0m"
        continue
    }
done

# 在每台服务器上执行脚本
for server in "${servers[@]}"; do
    echo -e "\033[33m在 $server 上执行脚本...\033[0m"
    sshpass -p 'l' ssh -T -o StrictHostKeyChecking=no \
        lhx@"$server" "chmod +x ${REMOTE_PATH}/${SEND_SCRIPT##*/} && ${REMOTE_PATH}/${SEND_SCRIPT##*/}" && {
	echo -e "\033[32m$server 执行成功\033[0m"
    } || {
	echo -e "\033[31m$server 执行失败\033[0m"
        continue
    }
done
